﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using ICSharpCode.SharpZipLib.Zip;
using MengXunAppTool.DAL;
using MengXunAppTool.Helper;
using MesTool.Model;
using 软件发布平台.View;


namespace 软件发布平台
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private VerDAL verDAL = new VerDAL();
        private ReleaseView releaseView = new ReleaseView();
        private ConfigHelper configHelper = new ConfigHelper();
        public static MesTool.Model.UserModel userModel = null;
        public MainWindow()
        {
            try
            {

                var view = new View.LoginView();
                bool? isIn = view.ShowDialog();
                this.Focus();
                if (userModel == null)
                {
                    userModel = new MesTool.Model.UserModel() { nickName = "User" };
                }
                else
                {
                    if (releaseView.viewModel.ReleaseUsers.Contains(userModel.nickName))
                    {
                        releaseView.viewModel.FbUser = userModel.nickName;
                    }
                }
                string customer = "盟讯";
                string product = "通用";
                string softwarename = "软件发布平台";
                string lastVer = verDAL.GetLastVer(customer, product, softwarename);
                Dictionary<string, string> dic = configHelper.ReadAll(System.Environment.CurrentDirectory + "\\Update\\自动升级工具.exe.config");
                string localVer = dic["Version"];
                if (localVer != lastVer)
                {
                    Process process1 = new Process();
                    process1.StartInfo.WorkingDirectory = System.Environment.CurrentDirectory + "\\Update";
                    process1.StartInfo.FileName = "自动升级工具.exe";
                    process1.Start();
                    this.Close();
                    return;
                }
                //if (File.Exists(System.Environment.CurrentDirectory + "\\软件发布平台" + localVer + ".zip"))
                //{
                //    FileInfo zipFile = new FileInfo(System.Environment.CurrentDirectory + "\\软件发布平台" + localVer + ".zip");
                //    FileInfo updateFile = new FileInfo(System.Environment.CurrentDirectory + "\\Update\\自动升级工具.exe");
                //    if (zipFile.LastWriteTime > updateFile.LastWriteTime)
                //    {
                //        Decompress(zipFile.FullName, zipFile.FullName.Substring(0, zipFile.FullName.LastIndexOf('\\')));
                //        configHelper.Write(System.Environment.CurrentDirectory + "\\Update\\自动升级工具.exe.config", "Version", localVer);
                //    }
                //}
                InitializeComponent();
                releaseView.mainWindow = this;
                Win32Helper.CreateDesktopShortcut("软件发布平台", System.Environment.CurrentDirectory + "\\软件发布平台.exe");
                Rect rect = Win32Helper.GetWindowsRect();
                if (rect.Width < 1920)
                {
                    this.Width = rect.Width - 200;
                    this.Height = rect.Height - 200;
                }
                this.Title = "软件发布平台" + localVer;
                user.Text = userModel.nickName;
                appRecordView = new View.AppRecordView();
            }
            catch (Exception ee)
            {
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
               LogHelper.WriteLog(ee.ToString());
                this.Close();
            }
        }

        private void window_Closed(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }
        private void Grid_MouseMove(object sender, MouseEventArgs e)
        {
            Grid grid = sender as Grid;
            if (grid.Background==null || (grid.Background as SolidColorBrush).Color.R != 8)
            {
                grid.Background = new SolidColorBrush(Color.FromRgb(7, 125, 224));
            }
        }
        private void Grid_MouseLeave(object sender, MouseEventArgs e)
        {
            Grid grid = sender as Grid;
            if ((grid.Background as SolidColorBrush).Color.R!=8)
            {
                grid.Background = BaseGrid.Background;
            }
        }

        private void ReleaseGrid1_MouseUp(object sender, MouseButtonEventArgs e)
        {
            ReleaseGrid1.Background = new SolidColorBrush(Color.FromRgb(8, 125, 224));
            ReleaseGrid2.Background = BaseGrid.Background;
            ReleaseGrid3.Background = BaseGrid.Background;
            GridMain.Children.Clear();
            GridMain.Children.Add(releaseView);
        }
        private void ReleaseGrid2_MouseUp(object sender, MouseButtonEventArgs e)
        {
            ReleaseGrid1.Background = BaseGrid.Background;
            ReleaseGrid2.Background = new SolidColorBrush(Color.FromRgb(8, 125, 224));
            ReleaseGrid3.Background = BaseGrid.Background;
            GridMain.Children.Clear();
            GridMain.Children.Add(appRecordView);
        }
        private View.AppRunRecordView runRecordView = new View.AppRunRecordView();
        public View.AppRecordView appRecordView = null;
        private void ReleaseGrid3_MouseUp(object sender, MouseButtonEventArgs e)
        {
            ReleaseGrid1.Background = BaseGrid.Background;
            ReleaseGrid2.Background = BaseGrid.Background;
            ReleaseGrid3.Background = new SolidColorBrush(Color.FromRgb(8, 125, 224));
            GridMain.Children.Clear();
            GridMain.Children.Add(runRecordView);
        }

        public void Login_Click(object sender, RoutedEventArgs e)
        {
            bool? dialog = new View.LoginView().ShowDialog();
            if (dialog==true)
            {
                if (user.Text != userModel.nickName)
                {
                    user.Text = userModel.nickName;
                    appRecordView.InitRecord();
                    releaseView.viewModel.FbUser = userModel.nickName;
                }            
            }
        }

        private void PopupBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                //位置
                contextMenu.PlacementTarget = box;
                contextMenu.Placement = PlacementMode.Bottom;
                contextMenu.HorizontalOffset = -126;
                //显示菜单
                contextMenu.IsOpen = true;
            }
            catch (Exception ee)
            {
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
               LogHelper.WriteLog(ee.ToString());
            }
        }

        private void Logout_Click(object sender, RoutedEventArgs e)
        {
            user.Text = "User";
            if (user.Text != userModel.nickName)
            {
                userModel.nickName = "User";
                appRecordView.InitRecord();
            }
        }
        public static bool IsFileInUse(string fileName)
        {
            bool inUse = true;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read,
                FileShare.None);
                inUse = false;
            }
            catch
            {
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
            return inUse;//true表示正在使用,false没有使用  
        }
        public void Decompress(string GzipFile, string targetPath)
        {
            string directoryName = targetPath;
            if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解压目录    
            string CurrentDirectory = directoryName;
            byte[] data = new byte[2048];
            int size = 2048;
            ZipEntry theEntry = null;
            long count;
            using (FileStream fsFile = new FileStream(GzipFile, FileMode.OpenOrCreate))
            {
                ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(fsFile);
                count = zipFile.Count;
            }
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile)))
            {
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.IsDirectory)
                    {// 该结点是目录    
                        if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name);
                    }
                    else
                    {
                        if (theEntry.Name != String.Empty)
                        {
                            //  检查多级目录是否存在  
                            if (theEntry.Name.Contains("/"))
                            {
                                string parentDirPath = theEntry.Name.Remove(theEntry.Name.LastIndexOf("/") + 1);
                                if (!parentDirPath.Equals("Update/"))
                                {
                                    continue;
                                }
                                if (!Directory.Exists(CurrentDirectory + "\\" + parentDirPath))
                                {
                                    Directory.CreateDirectory(CurrentDirectory + "\\" + parentDirPath);
                                }
                                while (IsFileInUse(CurrentDirectory + "\\" + theEntry.Name))
                                {
                                    Thread.Sleep(200);
                                }
                                using (FileStream streamWriter = File.Create(CurrentDirectory + "\\" + theEntry.Name))
                                {
                                    while (true)
                                    {
                                        size = s.Read(data, 0, data.Length);
                                        if (size <= 0) break;
                                        streamWriter.Write(data, 0, size);
                                    }
                                    streamWriter.Close();
                                }
                            }
                        }
                    }
                }
                s.Close();
            }
        }
    }

}